package com.srwl.mytx.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.TaskRecordAdapter;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Task;
import com.srwl.mytx.service.TaskService;
import com.srwl.mytx.widget.NodataFooter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import me.dkzwm.widget.srl.extra.footer.MaterialFooter;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class PublishTaskRecordFragment extends BaseFragment {
    private static final String TAG = PublishTaskRecordFragment.class.getSimpleName();
    @BindView(R.id.refresh_layout)
    MaterialSmoothRefreshLayout refreshLayout;
    @BindView(R.id.rl_task)
    RecyclerView rl_task;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;

    private TaskRecordAdapter taskRecordAdapter;
    private List<Task> taskList = new ArrayList<>();
    private int page = 1;
    private boolean hasNextPage;

    public static PublishTaskRecordFragment newInstance() {
        PublishTaskRecordFragment fragment = new PublishTaskRecordFragment();

        return fragment;
    }


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_task_record, container, false);
        ButterKnife.bind(this,view);
        taskRecordAdapter = new TaskRecordAdapter(getActivity(), taskList);
        rl_task.setLayoutManager(new LinearLayoutManager(getActivity(), RecyclerView.VERTICAL, false));
        rl_task.setAdapter(taskRecordAdapter);
        loadData(true, false);
        initRefreshLayout();
        return view;
    }



    private void initRefreshLayout() {
        refreshLayout.setDisableRefresh(false);
        refreshLayout.setDisableLoadMore(false);
        refreshLayout.setEnableOverScroll(false);
        refreshLayout.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {
                page = 1;

                if (refreshLayout.getFooterView() instanceof NodataFooter) {
                    refreshLayout.setFooterView(new MaterialFooter(getActivity()));

                }
                loadData(false, true);
            }

            @Override
            public void onLoadingMore() {
                if (hasNextPage) {
                    loadData(false, false);
                } else {
                    refreshLayout.refreshComplete();
                }
            }

        });
    }


    private void loadData(boolean isFirst, boolean isRefresh) {
        if (!Helper.getInstance().isNetworkConnected()){
            if (!isFirst) refreshLayout.refreshComplete();
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        int SIZE = 20;
        Map<String, Object> body = new HashMap<>();
        body.put("page", page);
        body.put("size", SIZE);
        if (isFirst) {
            progressBar.setVisibility(View.VISIBLE);
        }
        RetrofitManager.getInstance().createRequest(TaskService.class)
                .queryPublishTask(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (isFirst) {
                            progressBar.setVisibility(View.INVISIBLE);
                        } else {
                            refreshLayout.refreshComplete();
                        }

                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        JSONObject pageInfo = (JSONObject) result.getData();
                        Log.d(TAG, "onResponse: 获取个人出价记录完成" + pageInfo.toJSONString());
                        hasNextPage = pageInfo.getBoolean("hasNextPage");
                        if (!hasNextPage) {
                            refreshLayout.postDelayed(() -> {
                                if (getActivity() != null) {
                                    refreshLayout.setFooterView(new NodataFooter(getActivity()));
                                }
                            }, 1000);
                        }

                        List<Task> orders = pageInfo.getJSONArray("list").toJavaList(Task.class);
                        if (isRefresh) {
                            taskList.clear();
                        }
                        taskList.addAll(orders);
                        taskRecordAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        if (isFirst) {
                            progressBar.setVisibility(View.INVISIBLE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode != Activity.RESULT_OK || data == null) {
            return;
        }

    }

}
